package com.k.kpp.config.http;

import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.hc.client5.http.classic.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author k
 */
public class HttpClientTemplate {
    private final static Logger LOGGER = LoggerFactory.getLogger(HttpClientTemplate.class);
    private ObjectPool<HttpClient> pool;
    public HttpClientTemplate(HttpClientFactory factory,GenericObjectPoolConfig poolConfig) {
        System.out.println("ftp.pool:"+poolConfig.toString());
        this.pool = new GenericObjectPool<HttpClient>(factory,poolConfig);
    }

    public String doPost(){
        System.out.println("method: uploadFile");
        String result;
        HttpClient client = null;
        try {
            client = getClient();
            result = "";
        } catch (Exception e) {
            LOGGER.error("uploadFile error:{}",e);
            result = "";
            e.printStackTrace();
        }finally {
            clearClient(client);
        }
        return result;
    }
    private HttpClient getClient() throws Exception {
        return pool.borrowObject();
    }
    private void clearClient(HttpClient client){
        if(client!=null){
            try {
                pool.returnObject(client);
            } catch (Exception e) {
                // ignore
            }
        }
    }
}
